/*
Source : https://leetcode.com/problems/3sum-closest/
Author : nflush@outlook.com
Date   : 2016-08-22
*/
/*
16. 3Sum Closest

    Total Accepted: 89578
    Total Submissions: 299423
    Difficulty: Medium

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Subscribe to see which companies asked this question
Have you met this question in a real interview?
*/
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int min_dis = target;
        int i=0,j=0,k,te;
        int max = nums.size();
        min_dis = nums[max-1] + nums[max-2]+nums[max-3];
        te = min_dis;
        if (min_dis > target) {
            min_dis -= target;
        } else {
            min_dis = target - min_dis;
        }
        for (i=0;i<max-2;i++){
            if(i!=0&&nums[i]==nums[i-1]) continue;
            for (j=i+1, k=max-1;j<k;){
                if(j!=i+1&&nums[j]==nums[j-1]){
                    j++;
                    continue;
                }
                int sum = nums[i]+nums[j]+nums[k];
                if (sum == target){
                    return target;
                } else if(sum > target){
                    k--;
                    if (min_dis > (sum - target)){
                        min_dis = (sum - target);
                        te = sum;
                    }
                } else {
                    j++;
                    if (min_dis > (target - sum)){
                        min_dis = (target - sum);
                        te = sum;
                    }
                }
            }
        }
        return te;
    }
};

